var app = getApp();
var util = require("../../utils/util.js");
var siteinfo = require('../../siteinfo.js');
var answerList = [] //答案合集：id+value
//实现单选、多选
Page({
    data: {
        inputIndex: 0,
        index: 0, // 题目序列
        questionList: [],
        isShowAnswer: false,//是否展示答案
        myData: {},
        profileId: '',
        num: '',
        dxAnswer: '11',
        dxEvent: {},
        isSubmit:false
    },
    onLoad: function (options) {
        var _this = this
        _this.setData({
            myData: options
        })
        var profileId = options.id
        // var num = wx.getStorageSync('num')
        var num = options.num
        _this.setData({
            profileId: profileId,
            num: num
        })
        _this.getPractice()
        wx.setNavigationBarTitle({
            title: '题库练习'
        })
    },
    onShow: function () {

    },
    getIndex: function (e) {
        var value = e.detail.value;
        this.setData({
            inputIndex: value
        });
    },

    handleSubmit: function (arr) {
        console.log(arr, 'arr');
        let dataList = arr.map(item => {
            return {
                practiceId: item.id,
                value: item.value ? item.value.replace(/;;/g, '') : '',
                answer: item.answer,
                score: item.score,
                introduce:item.introduce,
                topicTypes:item.topicTypes,
                options:item.options.map(item=>`${item.code}、${item.content}`).join(';;')
            }
        })
        var that = this
        that.setData({
            isSubmit:true
        })
        let token = wx.getStorageSync('token');
        wx.request({
            url: siteinfo.siteroot3 + 'jzApi/jzPaperPracticeRecord/addPaper',
            header: {
                'Authorization': token,
                'content-type': 'application/json'
            },
            data: {
                paperId: this.data.myData.id,
                name: this.data.myData.name,
                list: dataList
            },
            method: 'POST',
            success: function (res) {
                if(res.data.code!=='0'){
                    app.showError(res.data.msg)
                    return false;
                }
                wx.showModal({
                    title: '提示',
                    content: '您的总分为' + res.data.data + '分',
                    showCancel: false,
                    success: function (res) {
                        answerList = []
                        that.setData({
                            isSubmit:false
                        })
                        if (res.confirm) {
                            answerList = []
                            _this.setData({
                                isShowAnswer: true
                            })
                        }
                    }
                })
            }
        });
    },

    //获取题目数据
    getPractice: function () {
        var _this = this
        app._post_form(siteinfo.selYuyinExaminationPaper, {
            profileId
                : _this.data.profileId, num: _this.data.num
        }, function (result) {
            //计时
            util.calculagraph(_this)
            //  _this.setInterval(result.data.endTime)
            var practiceList = result.data.questions
            for (var i = 0; i < practiceList.length; i++) {
                practiceList[i].options = practiceList[i].options.split(";;")
                practiceList[i].checked = false
                for (var j = 0; j < practiceList[i].options.length; j++) {
                    practiceList[i].options[j] = {
                        "score": 0,
                        "code": practiceList[i].options[j].substring(0, 1),
                        "content": practiceList[i].options[j].substring(2, practiceList[i].options[j].length),
                        "checked": false
                    }
                }
            }
            _this.setData({
                questionList: practiceList, // 拿到答题数据
                tpaperId: result.data.id
            })
        })
    },
    /*
     * 单选事件
     */
    radioChange: function (e) {
        var _this = this
        var questionList = _this.data.questionList
        _this.setData({
            dxAnswer: e.detail.value
        })
        var index = _this.data.index
        for (var i = 0; i < questionList.length; i++) {
            if (questionList[index].id == questionList[i].id) {
                for (var j = 0; j < questionList[index].options.length; j++) {
                    //渲染答卷选项
                    if (e.detail.value == questionList[index].options[j].code) {
                        questionList[index].options[j].checked = true
                    } else {
                        questionList[index].options[j].checked = false
                    }
                }
                questionList[i].value = e.detail.value
            }
        }
        _this.setData({
            questionList: questionList
        })
    },
    // 查看多选答案
    checkAnswer: function (params) {
        // if (!this.dxEvent) {
        //     app.showError('选择一个选项之后可查看答案!')
        //     return;
        // }
        let e = this.dxEvent
        console.log(this.dxEvent, 'this.dxEvent');
        if (!this.dxEvent) {
            return;
        }
        var _this = this
        _this.data.dxAnswer = e.detail.value
        _this.setData({
            dxAnswer: e.detail.value.sort().join('')
        })
        console.log(_this.data.dxAnswer, '_this.data.dxAnswer');
        var questionList = _this.data.questionList
        var index = _this.data.index
        for (var i = 0; i < questionList.length; i++) {
            if (questionList[index].id == questionList[i].id) {
                for (var j = 0; j < questionList[index].options.length; j++) {
                    questionList[index].options[j].checked = false
                    for (var b = 0; b < e.detail.value.length; b++) {
                        //渲染答卷选项
                        if (e.detail.value[b] == questionList[index].options[j].code) {
                            questionList[index].options[j].checked = true
                        }
                    }
                    console.log(e.detail.value);
                    questionList[i].value = e.detail.value

                }
            }
        }
        this.dxEvent = ''
        _this.setData({
            questionList: questionList
        })
    },
    /*
     * 多选事件
     */
    checkboxChange: function (e) {
        this.dxEvent = e
    },
    goTo: function () {
        var _this = this
        var i = _this.data.inputIndex
        if (i >= 1 && i <= _this.data.questionList.length) {
            _this.setData({
                index: i - 1
            })
        } else {
            _this.setData({
                inputIndex: _this.data.index + 1
            })
            return;
        }
    },
    // 上一题
    prev: function () {
        var _this = this
        if (_this.data.questionList[_this.data.index].topicTypes == 1) {
            this.checkAnswer()
        }
        if (_this.data.index != 0) {
            // 渲染下一题
            _this.setData({
                index: _this.data.index - 1
            })
        }
        console.log(this.data.questionList[this.data.index], 'prev');
        
        // this.checkAnswer()
    },
    sumitPaper: function () {
        var _this = this
        //格式化答卷格式id+value
        for (var i = 0; i < _this.data.questionList.length; i++) {
            if (typeof (_this.data.questionList[i].value) == 'object') {
                var bb = ''
                for (var j = 0; j < _this.data.questionList[i].value.length; j++) {
                    bb += _this.data.questionList[i].value[j] + ';;'
                }
                answerList.push({topicTypes:_this.data.questionList[i].topicTypes,  options:_this.data.questionList[i].options, introduce:_this.data.questionList[i].introduce, id: _this.data.questionList[i].id, value: bb, answer: _this.data.questionList[i].answer, score: _this.data.questionList[i].score });
            } else {
                answerList.push({topicTypes:_this.data.questionList[i].topicTypes,options:_this.data.questionList[i].options, introduce:_this.data.questionList[i].introduce, id: _this.data.questionList[i].id, value: _this.data.questionList[i].value, answer: _this.data.questionList[i].answer, score: _this.data.questionList[i].score });
            }
        }
        console.log("answerList", answerList)
        this.handleSubmit(answerList)
        //计算总分数
        // var allScore = 0;
        // for (var i = 0; i <= answerList.length - 1; i++) {
        //     if (answerList[i].value != undefined) {

        //         //单选，判断
        //         // if (answerList[i].value.toString().indexOf(";;") == -1) {
        //         //     if (answerList[i].value == answerList[i].answer) {
        //         //         allScore = allScore + answerList[i].score * 1
        //         //     }
        //         // } else {
        //         //     //多选
        //         //     var valueList = answerList[i].value.split(";;");
        //         //     //数组重新排序
        //         //     var valueList1 = valueList.slice(0, valueList.length - 1).sort()
        //         //     var answerList1 = answerList[i].answer.split(";;").sort();
        //         //     if (valueList1.length == answerList1.length) {
        //         //         var b = true;
        //         //         for (var a = 0; a < answerList1.length; a++) {
        //         //             if (valueList1[a] != answerList1[a]) {
        //         //                 b = false;
        //         //             }
        //         //         }
        //         //         if (b == true) {
        //         //             allScore = allScore + answerList[i].score * 1
        //         //         }
        //         //     }
        //         // }
        //     }
        // }
        // // 总分不能大于一百
        // if (allScore > 100) {
        //     allScore = 100
        // }
        // wx.showModal({
        //     title: '提示',
        //     content: '您的总分为' + allScore + '分',
        //     showCancel: false,
        //     success: function (res) {
        //         if (res.confirm) {
        //             answerList = []
        //             _this.setData({
        //                 isShowAnswer: true
        //             })
        //         }
        //     }
        // })
    },
    /*
     * 下一题/提交 按钮
     */
    nextSubmit: function () {
        var _this = this
        // const appInstance = getApp()
        // console.log(appInstance.globalData);
        // try {
        //   wx.setStorageSync('newCollect', appInstance.globalData);
        //   wx.showToast({
        //     title: '存储成功',
        //     icon: 'none',
        //     duration: 2000
        //   });
        // } catch (e) {
        //   wx.showToast({
        //     title: '存储失败',
        //     icon: 'none',
        //     duration: 2000
        //   });
        // }
        _this.setData({
            prevBtn: true
        })
        if (_this.data.questionList[_this.data.index].topicTypes == 1) {
            this.checkAnswer()
        }
        // 判断是不是最后一题
        if (_this.data.index < _this.data.questionList.length - 1) {
            // 渲染下一题
            _this.setData({
                index: _this.data.index + 1
            })

        } else {
            wx.showModal({
                title: '提示',
                content: '确定要提交答卷？',
                success: function (res) {
                    if (res.confirm) {
                        _this.sumitPaper()
                    }
                }
            })
        }
    },
})